const urlParams = new URLSearchParams(new URL(window.location.href).search);
let resourceId = urlParams.get('id');
let states = urlParams.get('state');

$(function () {
    load();
    if(states === '1') {
        $('#addFroms').hide()
    }
    $('.videoBox').on('click',function (){
        console.log($(this))
    })

    $('.overlays').click(function() {
        $(this).removeClass('active');
    });
});
let dateList = [
    {
        field: 'name',
        title: '标题',
    },
    {
        field: 'sort',
        title: '优先级'
    },
    {
        field: 'chapterDocuments',
        title: '视频信息',
        formatter: function(value, row, index) {
            let video = [];
            for (let i = 0; i < value?.length; i++) {
                if (value[i].type === '3') {
                    video.push(value[i]);
                }
            }
            let span = document.createElement('div');
            let links = '';
            for (let i = 0; i < video.length; i++) {
                let value = video[i].file.substring(video[i].file.lastIndexOf('/') + 1);
                let x = `<a style="display: block;max-width: 150px;color: #0b9b8d" class="btn-color textOverflow" href="#" title="${value}"  onclick="videoPlayback('${video[i].file}','视频')">${value}</a>`;
                links += x;
            }
            span.innerHTML = links;
            return span.outerHTML;
        }
    },
    {
        field: 'chapterDocuments',
        title: '文档信息',
        formatter: function (value, row, index) {
            let video = []
            for (let i = 0; i <value?.length ; i++) {
                if(value[i].type === '2') {
                    video.push(value[i])
                }
            }
            let span = document.createElement('div');
            let links = '';
            for (let i = 0; i < video.length; i++) {
                let value = video[i].file.substring(video[i].file.lastIndexOf('/') + 1);
                let x = `<a style="display: block;max-width: 150px;color: #0b9b8d" class="btn-color textOverflow" href="#" title="${value}" onclick="Documentexamine('${video[i].id}')">${value}</a>`;
                links += x;
            }
            span.innerHTML = links;
            return span.outerHTML;
        }
    },
    {
        field: 'chapterDocuments',
        title: '音频信息',
        formatter: function (value, row, index) {
            let video = []
            for (let i = 0; i <value?.length ; i++) {
                if(value[i].type === '5') {
                    video.push(value[i])
                }
            }
            let span = document.createElement('div');
            let links = '';
            for (let i = 0; i < video.length; i++) {
                let value = video[i].file.substring(video[i].file.lastIndexOf('/') + 1);
                let x = `<a style="display: block;max-width: 150px;color: #0b9b8d" class="btn-color textOverflow" title="${value}"  onclick="videoPlayback('${video[i].file}','音频')">${value}</a>`;
                links += x;
            }
            span.innerHTML = links;
            return span.outerHTML;
        }
    },
    {
        field: 'chapterDocuments',
        title: '压缩包信息',
        formatter: function (value, row, index) {
            let video = []
            for (let i = 0; i <value?.length ; i++) {
                if(value[i].type === '1') {
                    video.push(value[i])
                }
            }
            let span = document.createElement('div');
            let links = '';
            for (let i = 0; i < video.length; i++) {
                let value = video[i].file.substring(video[i].file.lastIndexOf('/') + 1);
                let x = `<a style="display: block;max-width: 150px;color: #0b9b8d" class="btn-color textOverflow" href="${video[i].file}" title="${value}" >${value}</a>`;
                links += x;
            }
            span.innerHTML = links;
            return span.outerHTML;
        }
    },
    {
        field: 'chapterDocuments',
        title: '图片信息',
        formatter: function (value, row, index) {
            let video = []
            for (let i = 0; i <value?.length ; i++) {
                if(value[i].type === '4') {
                    video.push(value[i])
                }
            }
            let span= document.createElement('div')
            let links = '';
            for (let i = 0; i < video.length; i++) {
                let x = `<img style="width: 50px;height: auto;margin-right: 10px" onclick="imageClick('${video[i].file}')" src="${video[i].file}"></img>`;
                links+= x
            }
            span.innerHTML = links;
            return span.outerHTML;
        }
    },
    {
        title: '操作',
        field: 'userName',
        formatter: function (value, row, index) {
            let encodedRow = encodeURIComponent(stringifyWithoutCircular(row));
            let x = `<a class="btn-color" href="#" title="下载"  mce_href="#" onclick="download('${row.id}')">下载</a>`;
            let d = `<a class="btn-color" href="#" title="添加"  mce_href="#" onclick="remove('${encodedRow}')">添加</a>`;
            let e = `<a class="btn-color" href="#" mce_href="#" title="编辑" onclick="edit('${row.id}')">编辑</a>`;
            let a = `<a class="btn-color" href="#" title="删除"  mce_href="#" onclick="deletes('${encodedRow}')">删除</a>`;
            if(states === '1') {
                return ''
            }
            if(row.level ==='2') {
                return e + a;
            }
            return d + e + a;

        }
    }
]
function formatTableUnit(value, row, index) {
    return {
        css: {
            "white-space": 'nowrap',
            "text-overflow": "ellipsis",
            "overflow": "hidden",
            "max-width":"100px"
        }
    }
}

function stringifyWithoutCircular(obj) {
    const cache = new Set();

    return JSON.stringify(obj, function(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (cache.has(value)) {
                // 如果已经访问过该对象，则返回一个占位符
                return '[Circular Reference]';
            }
            cache.add(value);
        }
        return value;
    });
}



function load() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'post', // 服务器数据的请求方式 get or post
                url:  "/chapter/getChapter", // 服务器数据的加载地址
                iconSize : 'outline',
                toolbar : '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                // //设置为limit则会发送符合RESTFull格式的参数
                queryParams: function (params) {
                    return {
                        //说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                        coursesId:urlParams.get('id'),
                        current:params.pageNumber,
                        size:params.pageSize,
                        name:$('#name').val(),
                        paging:0,
                        type:2,
                        isDeleted:0
                    };
                },
                responseHandler: function (res) {
                    console.log(res)
                    if(res.code !== '0') {
                        return {
                            "total": 0,//总数
                            "rows": []  //数据
                        };
                    }
                    return {
                        "total": res.data.total,//总数
                        "rows": res.data.records//数据
                    };
                },
                columns: dateList,

                //指定子id
                idField: 'id',
                expandAll: false, // 是否全部展开
                //在哪一列展开树形
                treeShowField: 'name',
                //指定父id列
                parentIdField: 'parentId',

                onResetView: function (data) {
                    //console.log('load');
                    $('#exampleTable').treegrid({
                        // initialState: 'collapsed',// 所有节点都折叠
                        initialState: 'collapsed',// 所有节点都展开，默认展开
                        treeColumn: 0,
                        // expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                        // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                        onChange: function () {
                            $('#exampleTable').bootstrapTable('resetWidth');
                        }
                    });

                    //只展开树形的第一级节点
                    // $('#exampleTable').treegrid('getRootNodes').treegrid('expand');

                },
            });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}


// 新增章节
function addResource() {
    layer.open({
        type: 2,
        title: '新增',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['1200px', '750px'],
        content:  `/chapter/add?resourceId=${resourceId}`// iframe的url
    });
}

// 删除
function deletes(row) {
   let data = JSON.parse(decodeURIComponent(row))
    delete data._last
    delete data._level
    delete data._nodes
    delete data._parent
    data.isDeleted = '1'
    let index = layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        save({chapterDOS:[{id:data.id}]})
    })
}

// 编辑章节
function edit(id) {
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['1200px', '750px'],
        content:  `/chapter/edit?id=${id}`// iframe的url
    });
}


//下载
function download(id) {
    console.log(id)
}

/**
 * @param resourceId 资源id
 * @param row 父章节
 */
//添加子章节
function remove(row) {
    let rows = JSON.parse(decodeURIComponent(row));
    localStorage.setItem('rows',JSON.stringify(rows))
    layer.open({
        type: 2,
        title: '添加',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['1200px', '750px'],
        content:  `/chapter/add?resourceId=${resourceId}`// iframe的url
    });
}


//删除接口
function save(data,index) {
    $.ajax({
        type : "POST",
        url : "/chapter/batchRemove",
        contentType: 'application/json',
        data : JSON.stringify(data),
        success : function(data) {
            if (data.code == 0) {
                layer.msg("操作成功");
                layer.close(index);
                reLoad();
            } else {
                layer.alert(data.msg)
                layer.close(index);
            }

        },
        error: function(xhr, status, error) {
            // 请求失败时的处理
            layer.msg(error);
            layer.close(index);
        }
    });

}

// 文档查看
function Documentexamine(id) {
    $.ajax({
        url: "/couInfo/documentConversion",
        type: "POST",
        data: {
            resourceId: id
        },
        dataType: "json",
        success: function (r) {
            if(r.code=='200'||r.code==200){
                if(r.data.pdfUrl){
                    //http只能进行下载本地临时地址访问
                    $.ajax({
                        url: r.data.pdfUrl,
                        mimeType: 'text/plain; charset=x-user-defined',
                        cache: true,
                        type: "GET",
                        async: false,
                        success: function (data) {
                            var rawLength = data.length;
                            var array = new Uint8Array(new ArrayBuffer(rawLength));
                            for (i = 0; i < rawLength; i++) {
                                array[i] = data.charCodeAt(i) & 0xff;
                            }
                            //上面是把后台请求到的文件流进行转化为符合的流
                            var blob = new Blob([array],{type: 'application/pdf;charset-UTF-8'});
                            let file=window.URL.createObjectURL(blob)
                            layer.open({
                                type: 2,
                                title: '预览',
                                closeBtn: 1,
                                area: [ '1200px', '700px' ],
                                fixed: false,
                                maxmin: true,
                                content:file
                            });

                        },
                        error: function (err) {
                            console.log("错误")
                        }
                    });
                }else{
                    layer.msg("请重试")
                }
            }else{
                layer.msg("暂无数据")
            }
        },
        error: function (err) {
        }
    });
}

//视频播放
function videoPlayback(url,title) {
    let contens = `
        <div style="width: 500px;height: 300px;margin: 0 auto;margin-top: 65px">
         <video src="${url}" autoplay controls></video>
        </div>
    `
    layer.open({
        type: 1, // 弹框类型，这里是普通的页面层
        title: title, // 弹框标题
        content: contens, // 弹框内容，可以是 HTML 代码或 DOM 元素的选择器
        area: ['800px', '500px'], // 弹框的宽高
    });
}


// 图片查看
function imageClick(url) {
   $('.overlays').addClass('active');
   $('.overlays img').attr('src', url);
}